/**
 * 缓存依赖管理器
 * 管理不同缓存间的依赖关系，确保关联数据变更时清除相关缓存
 */
class CacheDependencyManager {
  constructor() {
    // 依赖关系图
    this._dependencies = {
      // 项目依赖
      'project': {
        // 当项目缓存变更时需要清除的其他缓存类型
        affects: ['task', 'document', 'team'],
        // 项目缓存的清除模式
        patterns: {
          // 项目ID关联的所有缓存
          byId: (id) => [
            { namespace: 'project', pattern: `^detail:${id}` },
            { namespace: 'task', pattern: `^project:${id}:` },
            { namespace: 'document', pattern: `^project:${id}:` },
            { namespace: 'team', pattern: `^project:${id}:` }
          ],
          // 项目列表相关缓存
          list: () => [
            { namespace: 'project', pattern: '^list:' }
          ],
          // 所有项目缓存
          all: () => [
            { namespace: 'project', pattern: '.*' }
          ]
        }
      },
      
      // 任务依赖
      'task': {
        affects: [],
        patterns: {
          byId: (id) => [
            { namespace: 'task', pattern: `^detail:${id}` }
          ],
          byProject: (projectId) => [
            { namespace: 'task', pattern: `^project:${projectId}:` }
          ],
          list: () => [
            { namespace: 'task', pattern: '^list:' }
          ],
          all: () => [
            { namespace: 'task', pattern: '.*' }
          ]
        }
      },
      
      // 文档依赖
      'document': {
        affects: [],
        patterns: {
          byId: (id) => [
            { namespace: 'document', pattern: `^detail:${id}` }
          ],
          byProject: (projectId) => [
            { namespace: 'document', pattern: `^project:${projectId}:` }
          ],
          list: () => [
            { namespace: 'document', pattern: '^list:' }
          ],
          all: () => [
            { namespace: 'document', pattern: '.*' }
          ]
        }
      },
      
      // 团队依赖
      'team': {
        affects: [],
        patterns: {
          byId: (id) => [
            { namespace: 'team', pattern: `^detail:${id}` }
          ],
          byProject: (projectId) => [
            { namespace: 'team', pattern: `^project:${projectId}:` }
          ],
          list: () => [
            { namespace: 'team', pattern: '^list:' }
          ],
          all: () => [
            { namespace: 'team', pattern: '.*' }
          ]
        }
      }
    };
    
    // 注册的缓存实例
    this._cacheInstances = {};
  }
  
  /**
   * 注册缓存实例
   * @param {String} namespace 缓存命名空间
   * @param {Object} cacheInstance 缓存实例
   */
  registerCache(namespace, cacheInstance) {
    if (!cacheInstance || typeof cacheInstance.removeByPattern !== 'function') {
      throw new Error(`缓存实例 ${namespace} 必须实现 removeByPattern 方法`);
    }
    
    this._cacheInstances[namespace] = cacheInstance;
  }
  
  /**
   * 获取已注册的缓存实例
   * @param {String} namespace 缓存命名空间
   */
  getCache(namespace) {
    return this._cacheInstances[namespace];
  }
  
  /**
   * 清除指定命名空间下匹配特定模式的缓存
   * @param {String} namespace 缓存命名空间
   * @param {String} pattern 正则表达式字符串
   */
  clearCache(namespace, pattern) {
    const cache = this._cacheInstances[namespace];
    if (cache) {
      cache.removeByPattern(pattern);
    }
  }
  
  /**
   * 清除与项目相关的缓存
   * @param {String} projectId 项目ID
   * @param {Boolean} includeList 是否包含列表缓存
   */
  clearProjectCache(projectId, includeList = true) {
    const patterns = this._dependencies.project.patterns.byId(projectId);
    
    if (includeList) {
      patterns.push(...this._dependencies.project.patterns.list());
    }
    
    this._clearPatterns(patterns);
  }
  
  /**
   * 清除与任务相关的缓存
   * @param {String} taskId 任务ID
   * @param {String} projectId 项目ID
   */
  clearTaskCache(taskId, projectId) {
    const patterns = [];
    
    // 特定任务缓存
    if (taskId) {
      patterns.push(...this._dependencies.task.patterns.byId(taskId));
    }
    
    // 项目下所有任务缓存
    if (projectId) {
      patterns.push(...this._dependencies.task.patterns.byProject(projectId));
    }
    
    this._clearPatterns(patterns);
  }
  
  /**
   * 清除与文档相关的缓存
   * @param {String} documentId 文档ID
   * @param {String} projectId 项目ID
   */
  clearDocumentCache(documentId, projectId) {
    const patterns = [];
    
    // 特定文档缓存
    if (documentId) {
      patterns.push(...this._dependencies.document.patterns.byId(documentId));
    }
    
    // 项目下所有文档缓存
    if (projectId) {
      patterns.push(...this._dependencies.document.patterns.byProject(projectId));
    }
    
    this._clearPatterns(patterns);
  }
  
  /**
   * 清除与团队成员相关的缓存
   * @param {String} memberId 成员ID
   * @param {String} projectId 项目ID
   */
  clearTeamCache(memberId, projectId) {
    const patterns = [];
    
    // 特定成员缓存
    if (memberId) {
      patterns.push(...this._dependencies.team.patterns.byId(memberId));
    }
    
    // 项目下所有成员缓存
    if (projectId) {
      patterns.push(...this._dependencies.team.patterns.byProject(projectId));
    }
    
    this._clearPatterns(patterns);
  }
  
  /**
   * 根据模式列表清除缓存
   * @param {Array} patterns 模式列表，每项包含namespace和pattern
   * @private
   */
  _clearPatterns(patterns) {
    patterns.forEach(({ namespace, pattern }) => {
      const cache = this._cacheInstances[namespace];
      if (cache) {
        cache.removeByPattern(pattern);
      }
    });
  }
  
  /**
   * 清除所有缓存
   */
  clearAllCache() {
    Object.keys(this._cacheInstances).forEach(namespace => {
      const cache = this._cacheInstances[namespace];
      if (cache && typeof cache.clear === 'function') {
        cache.clear();
      }
    });
  }
}

export const cacheDependencyManager = new CacheDependencyManager(); 